import logging
from lk_heuristic.models.node import Node2D
from lk_heuristic.models.tsp import Tsp
from lk_heuristic.utils.cost_funcs import cost_funcs


def solve_tsp_in_memory(points, solution_method="lk2_improve", runs=8, backtracking=(3, 3), reduction_level=4, reduction_cycle=4, tour_type="cycle", logging_level=logging.WARNING):
    """
    使用LKH算法在内存中直接求解TSP问题，无需.tsp文件。

    参数：
        points: List[Tuple[float, float]]
            二维点坐标列表，如 [(x1, y1), (x2, y2), ...]
        solution_method: str
            求解方法，可选："lk1_improve"、"lk2_improve"、"nn_improve"、"bf_improve"
        runs: int
            算法重复运行次数，取最优解
        backtracking: tuple
            回溯参数，默认(5,5)
        reduction_level: int
            启用边约简的起始level
        reduction_cycle: int
            启用边约简的起始cycle
        tour_type: str
            "cycle"为闭环TSP，"path"为路径TSP
        logging_level: int
            日志等级，默认WARNING

    返回：
        best_order: List[int]
            最优路径的点索引顺序（对应输入points的下标）
        best_cost: float
            最优路径长度

    用法示例：
        >>> from algorithm.tsp_solver import solve_tsp_in_memory
        >>> points = [(0,0), (1,0), (1,1), (0,1)]
        >>> order, cost = solve_tsp_in_memory(points)
        >>> print(order)  # 如 [0, 1, 2, 3]
        >>> print(cost)   # 路径总长
    """
    nodes = [Node2D(x, y) for x, y in points]
    cost_func = cost_funcs["EUC_2D"]
    best_order = None
    best_cost = float("inf")
    for _ in range(runs):
        tsp = Tsp(nodes, cost_func, shuffle=True, backtracking=backtracking, reduction_level=reduction_level, reduction_cycle=reduction_cycle, tour_type=tour_type, logging_level=logging_level)
        tsp.methods[solution_method]()
        tour_nodes = tsp.tour.get_nodes()
        order = [nodes.index(node) for node in tour_nodes]
        cost = tsp.tour.cost
        if cost < best_cost:
            best_cost = cost
            best_order = order
    return best_order, best_cost 